package config

import (
	"errors"

	"github.com/go-ini/ini"
)

// IPConfig 代理网站规则
type IPConfig struct {
	Host          string `json:"host"`          //网站主机名
	NextPage      string `json:"nextPage"`      //下一页规则
	Totals        string `json:"totals"`        //总页数
	IP            string `json:"ip"`            //默认IP
	UserAgent     string `json:"userAgent"`     //默认UserAgent
	Items         string `json:"items"`         //IP列表规则
	ItemIP        string `json:"itemIp"`        //代理IP规则
	ItemPort      string `json:"itemPort"`      //代理端口规则
	ItemAddress   string `json:"itemAddress"`   //代理地点
	ItemType      string `json:"itemType"`      //代理类型：https,http,tcp
	ItemAnonymous string `json:"itemAnonymous"` //代理是否匿名
	ItemSpeed     string `json:"itemSpeed"`     //代理速度
	ItemTime      string `json:"itemTime"`      //代理时间
}

// Config 爬虫配置
type Config struct {
	IPConfig    IPConfig
	ProcessName string
	RedisConfig RedisConfig
}

// RedisConfig Redis配置
type RedisConfig struct {
	Host      string
	IPPool    string
	IPPoolKey string
}

// NewIPConfig 新建Config
func NewIPConfig(section *ini.Section) *IPConfig {
	ipConfig := IPConfig{}
	ipConfig.Host = section.Key("host").String()
	ipConfig.NextPage = section.Key("nextPage").String()
	ipConfig.Totals = section.Key("totals").String()
	ipConfig.IP = section.Key("ip").String()
	ipConfig.UserAgent = section.Key("userAgent").String()
	ipConfig.Items = section.Key("items").String()
	ipConfig.ItemAddress = section.Key("itemAddress").String()
	ipConfig.ItemAnonymous = section.Key("itemAnonymous").String()
	ipConfig.ItemIP = section.Key("itemIp").String()
	ipConfig.ItemPort = section.Key("itemPort").String()
	ipConfig.ItemSpeed = section.Key("itemSpeed").String()
	ipConfig.ItemTime = section.Key("itemTime").String()
	ipConfig.ItemType = section.Key("itemType").String()
	return &ipConfig
}

// NewRedisConfig 新建对象
func NewRedisConfig(section *ini.Section) *RedisConfig {
	redisConf := RedisConfig{}
	if section == nil {
		redisConf.Host = "127.0.0.1:6379"
		redisConf.IPPoolKey = "ippoolkey"
		redisConf.IPPool = "ippool"
	} else {
		redisConf.Host = section.Key("host").String()
		redisConf.IPPoolKey = section.Key("ippoolkey").String()
		redisConf.IPPool = section.Key("ippool").String()
	}
	return &redisConf
}

// NewConfig 产生配置
func NewConfig(configPath string) (*Config, error) {
	conf, err := ini.Load(configPath)
	if err != nil {
		return nil, err
	}
	proxyIPSection := conf.Section("proxyIP")
	if proxyIPSection == nil {
		return nil, errors.New("proxyIp not found")
	}
	ipConfig := NewIPConfig(proxyIPSection)
	config := &Config{IPConfig: *ipConfig}
	// processName
	processName := conf.Section("global").Key("processName").String()
	if processName == "" {
		processName = "spider"
	}
	config.ProcessName = processName
	// redis
	config.RedisConfig = *NewRedisConfig(conf.Section("redis"))
	return config, nil
}
